package com.kpx.app.service;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.kpx.app.base.BaseService;
import com.kpx.app.bean.UploadBean;
import com.kpx.app.cache.FileCache;
import com.kpx.app.configs.BroadcastFilters;
import com.kpx.app.configs.Constants;
import com.kpx.app.http.HttpDataApi;
import com.kpx.app.http.HttpDataLoader;
import com.kpx.app.http.HttpDataReqUrl;
import com.kpx.app.http.ResObj;
import com.kpx.app.utils.ImagesBulkUpload;
import com.kpx.app.utils.MyHashMap;
import com.kpx.app.utils.uiutils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/4/5.
 */

public class UploadService extends BaseService {

    public static ArrayList<UploadBean> uploadBeens = new ArrayList<>();
    private boolean isNeedUpload = false;
    private ImagesBulkUpload imagesBulkUpload;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (imagesBulkUpload != null) {
                imagesBulkUpload.checkUpload(uploadBeens);
            }
            handler.sendEmptyMessageDelayed(0, 3000);
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        ArrayList<UploadBean> temuploadBeens = (ArrayList<UploadBean>) FileCache.sharedInstance().get(Constants.KEY_UPLOADS_LIST);
        if (temuploadBeens != null) {
            for (UploadBean b :
                    temuploadBeens) {
                if (b.getStatus() == UploadBean.UPLOAD_TYPE_WAITTING || !TextUtils.isEmpty(b.getLocalPath())) {
                    isNeedUpload = true;
                    uploadBeens.add(b.copy());
                }
            }
            FileCache.sharedInstance().put(Constants.KEY_UPLOADS_LIST, uploadBeens);
            if (isNeedUpload) {
                startUpload(temuploadBeens);
            }
        }
        handler.sendEmptyMessageDelayed(0, 3000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (imagesBulkUpload != null)
            imagesBulkUpload.cancelAll();
    }

    @Override
    public void onReceiver(Context context, Intent intent) {
        uploadBeens = (ArrayList<UploadBean>) FileCache.sharedInstance().get(Constants.KEY_UPLOADS_LIST);
        if (intent.getAction().equals(BroadcastFilters.BROADCAST_ACTION_UPLOAD_STATUS_CANCEL)) {
            UploadBean b = (UploadBean) intent.getSerializableExtra(Constants.KEY_UPLOAD_BEAN);
            if (b != null) {
                b.setStatus(UploadBean.UPLOAD_TYPE_STOP);
                refreshUploadStatus(b);
                imagesBulkUpload.cancelTask(b);
            }
        } else if (intent.getAction().equals(BroadcastFilters.BROADCAST_ACTION_UPLOAD_STATUS_BEGIN)) {
            UploadBean b = (UploadBean) intent.getSerializableExtra(Constants.KEY_UPLOAD_BEAN);
            if (b != null) {
                b.setStatus(UploadBean.UPLOAD_TYPE_UPLOADING);
                refreshUploadStatus(b);
                imagesBulkUpload.beginUpload(b);
            }
        } else if (intent.getAction().equals(BroadcastFilters.BROADCAST_ACTION_UPLOAD_STATUS_REBIND)) {
            UploadBean b = (UploadBean) intent.getSerializableExtra(Constants.KEY_UPLOAD_BEAN);
            if (b != null) {
                b.setStatus(UploadBean.UPLOAD_TYPE_BIND_ING);
                refreshUploadStatus(b);
                toBind(b);
            }
        } else if (intent.getAction().equals(BroadcastFilters.BROADCAST_ACTION_UPLOAD_ADD_PHOTOS)) {
            ArrayList<UploadBean> cacheBeens = (ArrayList<UploadBean>) FileCache.sharedInstance().get(Constants.KEY_UPLOADS_CACHE_LIST);
            if (cacheBeens != null) {
                addUploadFiles(cacheBeens);
                cacheBeens.clear();
                FileCache.sharedInstance().clear(Constants.KEY_UPLOADS_CACHE_LIST);
            }
        } else if (intent.getAction().equals(BroadcastFilters.BROADCAST_ACTION_UPLOAD_SERVICE_ASK)) {
            sendBroadcast(new Intent(BroadcastFilters.BROADCAST_ACTION_UPLOAD_SERVICE_ALIVE));
        }
    }

    /**
     * 添加需要上传的文件
     *
     * @param adds
     */
    private void addUploadFiles(ArrayList<UploadBean> adds) {
        if (uploadBeens == null) {
            uploadBeens = new ArrayList<>();
        }
        for (int i = 0; i < adds.size(); i++) {
            uploadBeens.add(0, adds.get(i).copy());
        }
        FileCache.sharedInstance().put(Constants.KEY_UPLOADS_LIST, uploadBeens);
        if (imagesBulkUpload != null) {
            imagesBulkUpload.addUploadFiles(adds);
        } else {
            startUpload(adds);
        }
    }

    /**
     * 开始上传
     *
     * @param uploads
     */
    private void startUpload(ArrayList<UploadBean> uploads) {
        imagesBulkUpload = new ImagesBulkUpload(this, uploads, true, new ImagesBulkUpload.OnBulkImagesUploadListener() {
            @Override
            public void onImageUploadProgress(UploadBean image, long progress, long total) {
                image.setUploaProgress((int) (progress * 100 / total));
                image.setStatus(UploadBean.UPLOAD_TYPE_UPLOADING);
                refreshUI(image);
            }

            @Override
            public void onImageUploadSucceed(UploadBean image) {
                image.setStatus(UploadBean.UPLOAD_TYPE_SUCCESSED);
                refreshUploadStatus(image);
                if (image.getUploadType() == UploadBean.TYPE_ORDER_IMG || image.getUploadType() == UploadBean.TYPE_PHOTO_IMG) {
                    toBind(image);
                }
            }

            @Override
            public void onImageUploadFailed(UploadBean image) {
                image.setStatus(UploadBean.UPLOAD_TYPE_FAIL);
                refreshUploadStatus(image);
            }

            @Override
            public void onFinished(List<UploadBean> imagesUploadFailed) {
                for (int i = 0; i < uploadBeens.size(); i++) {
                    for (int j = 0; j < imagesUploadFailed.size(); j++) {
                        if (uploadBeens.get(i).getLocalPath().equals(imagesUploadFailed.get(j).getLocalPath())) {
                            uploadBeens.get(i).setStatus(UploadBean.UPLOAD_TYPE_BIND_FAIL);
                            refreshUploadStatus(uploadBeens.get(i));
                        }
                    }
                }
            }
        });
        imagesBulkUpload.startUpload();
    }

    /**
     * 通知相关页面进行上传进度的刷新
     *
     * @param image
     */
    private void refreshUI(UploadBean image) {
        Intent intent = new Intent(BroadcastFilters.BROADCAST_ACTION_UPLOAD_STATUS_PROGRESS);
        intent.putExtra(Constants.KEY_UPLOAD_BEAN, image);
        sendBroadcast(intent);
    }

    /**
     * 图片进行订单的绑定
     *
     * @param image
     */
    private void toBind(final UploadBean image) {
        MyHashMap map = new MyHashMap();
        String url = "";
        if (image.getUploadType() == UploadBean.TYPE_ORDER_IMG) {
            url = HttpDataReqUrl.URL_BIND_PIC_ORDER;
            map.put("orderId", image.getBindOrderId());
            map.put("photos", image.getCloudKey());
        } else if (image.getUploadType() == UploadBean.TYPE_PHOTO_IMG) {
            map.put("imgUrl", image.getCloudKey());
            url = HttpDataReqUrl.URL_BIND_PIC_PHOTOS;
        }
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                if (result.getCode() == 0) {
                    image.setStatus(UploadBean.UPLOAD_TYPE_BIND_SUCCESS);
                } else if (result.getCode() == 20002) {
                    image.setStatus(UploadBean.UPLOAD_TYPE_BIND_FAIL_2);
                    image.setFailMsg(result.getMsg());
                } else {
                    image.setStatus(UploadBean.UPLOAD_TYPE_BIND_FAIL);
                }
                refreshUploadStatus(image);
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                image.setStatus(UploadBean.UPLOAD_TYPE_BIND_FAIL);
                refreshUploadStatus(image);
            }

        }, null, null).POST(url, true, map);
    }

    /**
     * 更新上传图片的状态
     *
     * @param image
     */
    private void refreshUploadStatus(UploadBean image) {
        for (int i = 0; i < uploadBeens.size(); i++) {
            if (uploadBeens.get(i).getImageID() == image.getImageID()) {
                uploadBeens.get(i).setStatus(image.getStatus());
                uploadBeens.get(i).setFailMsg(image.getFailMsg());
                break;
            }
        }
        FileCache.sharedInstance().put(Constants.KEY_UPLOADS_LIST, uploadBeens);
        refreshUI(image);
    }
}
